package com.xjm_cloud_admin.service;

import com.xjm_cloud_admin.constant.Constants;
import com.xjm_cloud_admin.domain.XjmFile;
import com.xjm_cloud_admin.domain.vo.resp.FileListRespVo;
import com.xjm_cloud_admin.enums.FileTypeEnum;
import com.xjm_cloud_admin.util.CommonUtils;
import com.xjm_cloud_admin.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.stream.Collectors;

public interface BaseFileService {


    default List<FileListRespVo> transformTree(List<XjmFile> fileList, String ip, String port) {
        return fileList.stream().map(x -> {
            FileListRespVo fileListRespVo = new FileListRespVo();
            fileListRespVo.toFileListRespVo(x);
            if (x.getType().equals(FileTypeEnum.VIDEO.getValue()) || x.getType().equals(FileTypeEnum.IMAGE.getValue())) {

                if ("webp".equalsIgnoreCase(CommonUtils.getFileNameSuffixNo(x.getPath()))) {
                    String previewPath = ip + "/pro-api" + Constants.RESOURCE_PREFIX + Constants.SEPARATOR + x.getPath();
                    fileListRespVo.setThumbnailPath(previewPath);
                    fileListRespVo.setPreviewPath(previewPath);
                } else {
                    String previewPath = ip + "/pro-api" + Constants.RESOURCE_PREFIX + Constants.SEPARATOR + x.getPath();
                    String thumbnailPath = previewPath + Constants.THUMB_IMG_SUFFIX;
                    fileListRespVo.setThumbnailPath(thumbnailPath);
                    fileListRespVo.setPreviewPath(previewPath);
                }
            }
            return fileListRespVo;
        }).collect(Collectors.toList());
    }

    default void readFile(String filePath, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(filePath)) {
            throw new RuntimeException("File not found");
        }
        File file = new File(filePath);

        if (!file.exists()) {
            // 文件不存在时返回404错误
            throw new RuntimeException("File not found");
        }

        FileInputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int length;

        while ((length = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
        }

        response.flushBuffer();
        inputStream.close();
        outputStream.close();
    }


}
